/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.lt.cj.core;

import org.lt.cj.config.entities.ConfigModel;
import org.lt.cj.core.server.entity.TaskState;
import org.lt.cj.core.utils.CommandList;

/*
 * @author luohong
 */
public class TaskImpl implements Task {

    private ConfigModel configModel;
    private String taskName;
    private CrawlerThreadGroup threadGroup;
    private String command;                                                     //执行命令，开始start|暂停pause|停止stop

    public TaskImpl(ConfigModel configModel) {
        this.configModel = configModel;
    }

    private void initTask() {                                                  //任务初始化的工作
        threadGroup = new CrawlerThreadGroup(taskName);                         //创建线程组，就像确定项目的名称

    }

    private void processtask() {
        threadGroup.accessTaskPaper(configModel);                               //项目组的人接收任务
    }

    public void processTask() {
        initTask();
        processtask();
    }

    public TaskState getTaskState() {

        TaskState state = new TaskState();
        state.setTaskName(taskName);
        state.setThreadCount(configModel.getWorkingThreads());
        state.setCurrentThreadCount(threadGroup.getCurrentWorkingThreadCount());
        state.setQueueURL("" + getLinkDB().getQueueUnvisitedUrlCount());
        return state;
    }

    public String takeOrder(String order) {                                     //执行命令

        String msg = "";
        if (order.trim().equals(CommandList.pauseCommand)) {                    //"pause"
            Thread[] list = new Thread[threadGroup.activeCount()];
            threadGroup.enumerate(list);
            threadGroup.pauseTask(list);
        } else if (order.trim().equals(CommandList.stopCommand)) {

            msg = this.threadGroup.stopTask();
            if (threadGroup.activeCount() == 0) {
                msg += "\n task already stopped";
            }
        } else if (order.trim().equals("go on")) {
            Thread[] list = new Thread[threadGroup.activeCount()];
            threadGroup.enumerate(list);
            threadGroup.resumeTask(list);
        }
        return msg;
    }

    public ConfigModel getConfigModel() {
        return configModel;
    }

    public void setConfigModel(ConfigModel configModel) {
        this.configModel = configModel;
    }

    public String getTaskName() {
        return taskName;
    }

    public void setTaskName(String taskName) {
        this.taskName = taskName;
    }

    public LinkDB getLinkDB() {
        return threadGroup.getLinkDB();
    }
}
